package com.mashibing.service.impl.redisImpl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RenewRedisLockService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 将锁进行时间续签
     *
     * @param driverId
     * @param orderIdKey
     * @param timePeriod
     */
    @Async
    public void renewRedisLock(String driverId, String orderIdKey, int timePeriod) {
        System.out.println("异步加锁");
        String value = stringRedisTemplate.opsForValue().get(orderIdKey);

        if (!StringUtils.isBlank(value) && value.equals(driverId)) {
            int renewTimePeriod = timePeriod / 3;
            try {
                TimeUnit.SECONDS.sleep(renewTimePeriod);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            stringRedisTemplate.expire(orderIdKey, timePeriod, TimeUnit.SECONDS);
        } else {
            return;
        }
        renewRedisLock(driverId, orderIdKey, timePeriod);
    }
}
